import React, { useCallback, useEffect, useMemo } from 'react';
import {
    SafeAreaView,
    ScrollView,
    View,
    Text,
    StyleSheet,
    BackHandler,
    TouchableOpacity,
    Image,
} from 'react-native';

import { getStatusBarHeight } from '../../../utils/statusBarHeight';
import fanhui from '../../../assets/fanhui.png';

interface TaskDetailScreenProps {
    route: {
        params?: {
            task?: any;
        };
    };
    navigation: {
        goBack?: () => void;
    };
}

const formatValue = (value: any) => {
    if (value === null || value === undefined || value === '') {
        return '-';
    }
    return String(value);
};

const formatProgress = (value: any) => {
    if (value === null || value === undefined || Number.isNaN(Number(value))) {
        return '0%';
    }
    return `${Number(value)}%`;
};

const TaskDetailScreen: React.FC<TaskDetailScreenProps> = ({ route, navigation }) => {
    const task = route?.params?.task;

    const handleGoBack = useCallback(() => {
        navigation?.goBack?.();
    }, [navigation]);

    useEffect(() => {
        const subscription = BackHandler.addEventListener('hardwareBackPress', () => {
            handleGoBack();
            return true;
        });

        return () => subscription.remove();
    }, [handleGoBack]);

    if (!task) {
        return (
            <SafeAreaView style={styles.container}>
                <View style={styles.headerContainer}>
                    <TouchableOpacity onPress={handleGoBack} style={styles.backButton}>
                        <Image source={fanhui} style={styles.backIcon} />
                    </TouchableOpacity>
                    <Text style={styles.headerTitle}>任务详情</Text>
                    <View style={styles.headerPlaceholder} />
                </View>
                <View style={styles.emptyContainer}>
                    <Text style={styles.emptyText}>未找到任务信息</Text>
                </View>
            </SafeAreaView>
        );
    }

    const detailRows = useMemo(
        () => [
            { label: '工单号', value: formatValue(task.work_order_num) },
            { label: '批次号', value: formatValue(task.batch_order_num) },
            { label: '工序', value: formatValue(task.mbom_num) },
            { label: '工艺名称', value: formatValue(task.process_name) },
            { label: '计划数量', value: formatValue(task.quantity) },
            { label: '报工数量', value: formatValue(task.work_quantity) },
            { label: '报废数量', value: formatValue(task.fatal_quantity) },
            { label: '产品名称', value: formatValue(task.product_name) },
            { label: '产品编码', value: formatValue(task.product_encode) },
            { label: '产品型号', value: formatValue(task.product_model) },
            { label: '产品规格', value: formatValue(task.product_specs) },
            { label: '车间', value: formatValue(task.work_room_name || task.aps_room_name) },
            { label: '作业区', value: formatValue(task.group_name) },
            { label: '设备编号', value: formatValue(task.work_device_num || task.aps_device_num) },
            { label: '工位编号', value: formatValue(task.work_station_num || task.aps_station_num) },
            { label: '产线编号', value: formatValue(task.work_line_num || task.aps_line_num) },
            { label: '操作工', value: formatValue(task.work_user_name || task.aps_user_name) },
            { label: '开始时间', value: formatValue(task.aps_start) },
            { label: '结束时间', value: formatValue(task.aps_end) },
            { label: '最后报工时间', value: formatValue(task.update_time) },
        ],
        [task],
    );

    return (
        <SafeAreaView style={styles.container}>
            <View style={styles.headerContainer}>
                <TouchableOpacity onPress={handleGoBack} style={styles.backButton}>
                    <Image source={fanhui} style={styles.backIcon} />
                </TouchableOpacity>
                <Text style={styles.headerTitle}>任务详情</Text>
                <View style={styles.headerPlaceholder} />
            </View>
            <ScrollView contentContainerStyle={styles.listContent} showsVerticalScrollIndicator={false}>
                <View style={styles.listContainer}>
                    {detailRows.map((row, index) => (
                        <View
                            key={row.label}
                            style={[
                                styles.listRow,
                                index === detailRows.length - 1 && styles.listRowLast,
                            ]}
                        >
                            <Text style={styles.rowLabel}>{row.label}：</Text>
                            <Text style={styles.rowValue}>{row.value}</Text>
                        </View>
                    ))}
                </View>
            </ScrollView>
        </SafeAreaView>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f5f5f5',
    },
    headerContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        paddingTop: getStatusBarHeight(),
        paddingHorizontal: 16,
        height: 50 + getStatusBarHeight(),
        backgroundColor: '#fff',
        borderBottomWidth: StyleSheet.hairlineWidth,
        borderBottomColor: '#eee',
    },
    backButton: {
        width: 44,
        height: 44,
        justifyContent: 'center',
        alignItems: 'center',
    },
    backIcon: {
        width: 24,
        height: 24,
    },
    headerTitle: {
        fontSize: 18,
        color: '#333',
        fontWeight: 'bold',
    },
    headerPlaceholder: {
        width: 44,
        height: 44,
    },
    listContent: {
        paddingHorizontal: 10,
        paddingTop: 12,
        paddingBottom: 32,
    },
    listContainer: {
        backgroundColor: '#fff',
        borderRadius: 12,
        overflow: 'hidden',
        borderWidth: StyleSheet.hairlineWidth,
        borderColor: '#eee',
    },
    listRow: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        paddingHorizontal: 10,
        paddingVertical: 12,
        borderBottomWidth: 0.5,
        borderBottomColor: '#ebebeb',
        backgroundColor: '#fff',
    },
    listRowLast: {
        borderBottomWidth: 0,
    },
    rowLabel: {
        fontSize: 15,
        color: '#666',
    },
    rowValue: {
        fontSize: 15,
        color: '#333',
        marginLeft: 20,
        flex: 1,
        textAlign: 'right',
        fontWeight: '500',
    },
    emptyContainer: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        padding: 24,
    },
    emptyText: {
        fontSize: 16,
        color: '#888',
    },
});

export default TaskDetailScreen;


